package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 关注或取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1 检查参数
        if (dto.getOperation()==null|| dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否有作者
        if (dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"作者信息不能为空");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2 获取作者
        ApAuthor apAuthor = articleFeign.findByUserId(dto.getAuthorId());
        if (apAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注人不存在");
        }
        if (dto.getOperation()==0){
            //关注，创建数据
            return followByUserId(user,apAuthor.getUserId(),dto.getArticleId());
        }else {
            //取消关注，删除数据
            return cancelByUserId(user,apAuthor.getUserId());
        }
    }

    @Override
    public boolean getFollowStatus(Long userId, Long followId) {
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followId)
                .eq(ApUserFollow::getUserId, userId));
        if (apUserFollow==null){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 取消关注
     * @param user
     * @param followId
     * @return
     */
    private ResponseResult cancelByUserId(ApUser user, Integer followId) {
        //1 查询关注对象
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followId)
                .eq(ApUserFollow::getUserId, user.getId()));
        if (apUserFollow==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未关注");
        }else{
            //删除数据
            //查询粉丝信息
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getFansId, user.getId())
                    .eq(ApUserFan::getUserId, followId));
            if (apUserFan!=null){
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getUserId,followId)
                        .eq(ApUserFan::getFansId,user.getId()));
            }
            //删除关注信息
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getFollowId,followId)
                    .eq(ApUserFollow::getUserId,user.getId()));
            //返回
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    /**
     * 关注作者
     * @param loginUser  登录人
     * @param followId  作者对应的用户id
     * @param articleId 文章id  用户记录用户的行为 第十章使用
     * @return
     */
    private ResponseResult followByUserId(ApUser loginUser, Integer followId, Long articleId) {
        //获取作者
        ApUser followUser = apUserMapper.selectById(followId);
        if (followUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注用户不存在");
        }
        //保存关注数据
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, loginUser.getId())
                .eq(ApUserFollow::getFollowId, followUser.getId()));
        if (apUserFollow==null){
            //查询粉丝信息
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followUser.getId())
                    .eq(ApUserFan::getFansId, loginUser.getId()));
            //保存粉丝
            if (apUserFan==null){
                apUserFan=new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(loginUser.getId().longValue());
                apUserFan.setCreatedTime(new Date());
                apUserFan.setFansName(loginUser.getName());
                apUserFan.setLevel((short) 0);
                apUserFan.setIsShieldComment(false);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsDisplay(true);
                apUserFanMapper.insert(apUserFan);
            }
            //保存关注人
            apUserFollow = new ApUserFollow();
            apUserFollow.setFollowId(followId);
            apUserFollow.setUserId(loginUser.getId());
            apUserFollow.setLevel((short) 1);
            apUserFollow.setIsNotice(true);
            apUserFollow.setFollowName(followUser.getName());
            apUserFollow.setCreatedTime(new Date());
            apUserFollowMapper.insert(apUserFollow);

            // 记录关注行为
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setFollowId(followId);
            dto.setArticleId(articleId);
            dto.setUserId(loginUser.getId());
            //异步发送消息，保存关注行为
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"已关注");
    }
}
